#!/usr/bin/python

import urllib,urllib2,re,xbmcplugin,xbmcgui
import os,datetime,base64,httplib
from BeautifulSoup import BeautifulStoneSoup
from pyamf import remoting
pluginhandle = int(sys.argv[1])

################################ Common
txheaders = {
    'Referer': 'http://www.aetv.com/',
    'X-Forwarded-For': '12.13.14.15',
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US;rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)',
}
fanart_links = {
		'/hoarders/':'http://thetvdb.com/banners/fanart/original/109621-2.jpg',
		'/storage-wars/':'http://thetvdb.com/banners/fanart/original/207621-2.jpg',
		'/storage-wars-texas/':'http://thetvdb.com/banners/fanart/original/251596-1.jpg',
		'/storage-wars-new-york/':'http://www.aetv.com/storage-wars-new-york/images/home/promo_bg.jpg',
               }
icon_links = {
              '/billy-the-exterminator/':'http://thetvdb.com/banners/_cache/posters/166101-1.jpg',
              '/hoarders/':'http://thetvdb.com/banners/_cache/posters/109621-1.jpg',
              '/parking-wars/':'http://thetvdb.com/banners/_cache/posters/81343-1.jpg',
              '/storage-wars/':'http://thetvdb.com/banners/_cache/posters/207621-1.jpg',
	      '/storage-wars-texas/':'http://thetvdb.com/banners/_cache/posters/251596-1.jpg',
	      }



def getURL( url ):
    try:
        print 'A&E --> getURL :: url = '+url
	txdata = None
        global txheaders  
        req = urllib2.Request(url, txdata, txheaders)
        response = urllib2.urlopen(req)
	link=response.read()
	response.close()
    except urllib2.URLError, e:
        error = 'Error code: '+ str(e.code)
        xbmcgui.Dialog().ok(error,error)
        print 'Error code: ', e.code
        return False
    else:
        return link


def addLink(name,url,mode,iconimage='',plot='',season=0,episode=0,showname='',duration='',fanart=''):
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&thumbnail='+urllib.quote_plus(iconimage)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name,
                                           "Plot":plot,
                                           "Season":season,
                                           "Episode":episode,
                                           "Duration":duration,
                                           "TVShowTitle":showname})
   if fanart!='':
      liz.setProperty('fanart_image', fanart)
   liz.setProperty('IsPlayable', 'true')
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz)
   return ok

def addLink(name,url,mode,smil,iconimage='',plot='',season=0,episode=0,showname='',duration='',fanart='special://home/addons/plugin.video.ae/fanart.jpg'):
   name = name.encode('raw-unicode-escape')
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&smil='+urllib.quote_plus(smil)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name,
                                           "Plot":plot,
                                           "Season":season,
                                           "Episode":episode,
                                           "Duration":duration,
                                           "TVShowTitle":showname})
   if fanart!='':
      liz.setProperty('fanart_image', fanart)
   liz.setProperty('IsPlayable', 'true')
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz)
   return ok

def addDir(name,url,mode,iconimage='',plot='',fanart=''):
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&thumbnail='+urllib.quote_plus(iconimage)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot":plot})
   if fanart!='':
      liz.setProperty('fanart_image', fanart);
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz,isFolder=True)
   return ok

################################ Root listing
def ROOT():
   xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
   data = getURL("http://www.aetv.com/videos/display.jsp")
   show_pages = re.compile('href="(.+?)" onClick="trackHeaderPrimaryOp\(\'Video\',\'Full Episodes: (.+?)video/\'').findall(data)
   show_pages.extend(re.compile('href="(.+?)" onClick="trackHeaderPrimaryOp\(\'Shows\',\'(.+?)\'').findall(data))

   global fanart_links
   global icon_links 

   processed_shows = []
   for show in show_pages:
      url, pretty_name = show
      

      
      if url not in processed_shows and show[0] != "/allshows.jsp":
         processed_shows.append(url)
         print "URL:%s Name:%s" % (url, pretty_name)
         mode=3 #EPISODE Mode
         fanart = 'special://home/addons/plugin.video.ae/fanart.jpg'
         icon = 'special://home/addons/plugin.video.ae/icon.png'
         if url in fanart_links:
            fanart = fanart_links[url]
         if url in icon_links:
            icon = icon_links[url]
         addDir(pretty_name,url,mode,icon,'',fanart)
   xbmcplugin.endOfDirectory(pluginhandle)

def EPISODE(name, sid):
   showname = name
   xbmcplugin.setContent(pluginhandle, 'episodes')
   xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_NONE)

   global fanart_links 
   global icon_links 

   episode_list = getEpisodeList(sid)
   for episode in episode_list:
      name = episode[0]
      thumbnail = episode[1]
      duration = episode[2]
      plot = episode[3]
      smil = episode[4]
      seasonNum = 0;
      episodeNum = 0;
      mode = 5 #PLAYEPISODE
      fanart = 'special://home/addons/plugin.video.ae/fanart.jpg'
      if sid in fanart_links:
         fanart = fanart_links[sid]
      addLink(name,sid,mode,smil,thumbnail,plot,seasonNum,episodeNum,showname,duration,fanart)

   xbmcplugin.endOfDirectory(pluginhandle)

def PLAYEPISODE(rtmp, smil):
     swfUrl="http://servicesaetn-a.akamaihd.net/video/pdk/swf/flvPlayer.swf"
     
     data = getURL(smil)

     eid = re.compile('-(\d+)').findall(smil)[0]

     sid = re.compile('mpxid:\''+eid+'\', videoURLs:{releaseURL:"http://link.theplatform.com/s/(.+?)\?').findall(data)[0]
     base = 'http://link.theplatform.com/s/'+sid

     sig = getURL('http://servicesaetn-a.akamaihd.net/jservice/video/components/get-signed-signature?url='+sid)

     url = base+'?sig='+sig+'&format=SMIL&Tracking=true&Embedded=true'
     data = getURL(url)


     rtmp_base = re.compile('<meta base="(.+?)"/>').findall(data)[0]
     playpath = re.compile('<video src="(.+?)"').findall(data)[0]
     playpath.replace("amp;", '')

     rtmp = rtmp_base+' swfurl='+swfUrl+' swfvfy=true playpath='+playpath+' pageurl=http://www.aetv.com'
     
     item = xbmcgui.ListItem(path=rtmp)
     return xbmcplugin.setResolvedUrl(pluginhandle, True, item)


def getEpisodeList(show):
   episode_list = []

   data = getURL('http://www.aetv.com/minisite/videoajx.jsp?homedir='+show+'&pfilter=FULL%20EPISODES')

   titles = re.compile('<p class="video_details-title">(.+?)</p>').findall(data)
   plots  = re.compile('<p class="video_details-synopsis">(.+?)</p>').findall(data)
   images = re.compile('<img id="carousel-img-\d+" realsrc="(.+?)"').findall(data)
   durations = re.compile('<span>(\d+:\d+)</span></p>').findall(data)
   urls = re.compile('onclick="goVid\(this,\'(.+?)\'').findall(data)

   print titles
   print plots
   print images
   print durations
   print urls

   for i in range(len(titles)):
      title = titles[i]
      plot  = plots[i]
      image = images[i]
      duration = durations[i]
      smil = urls[i]
      episode_list.append((title, image, duration, plot, smil))
   
   return episode_list
     

def get_params():
   param=[]
   paramstring=sys.argv[2]
   print paramstring
   if len(paramstring)>=2:
      params=sys.argv[2]
      cleanedparams=params.replace('?','')
      if (params[len(params)-1]=='/'):
         params=params[0:len(params)-2]
      pairsofparams=cleanedparams.split('&')
      param={}
      for i in range(len(pairsofparams)):
         splitparams={}
         splitparams=pairsofparams[i].split('=')
         if (len(splitparams))==2:
            param[splitparams[0]]=splitparams[1]
                                
   return param


params=get_params()
url=None
name=None
mode=None
smil=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        thumbnail=urllib.unquote_plus(params["thumbnail"])
except:
        thumbnail=''

try:
        smil=urllib.unquote_plus(params["smil"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Thumb:"+str(thumbnail)

if mode==None or url==None or len(url)<1:
   ROOT()
elif mode==1:
   pass
elif mode==2:
   pass
elif mode==3:
   EPISODE(name,url)
elif mode==4:
   pass
elif mode==5:
   PLAYEPISODE(url, smil)

	       
